"""
Exercise 1.
The Monte Carlo method can be used to generate an approximate value of pi.
Figure 1 below shows a unit square with a quarter of a circle inscribed.
The area of the square is 1 and the area of the quarter circle is pi/4.
Write a script to generate random points that are distributed uniformly in the unit square.
 The ratio between the number of points that fall inside the circle (red points) and the total number of points thrown (red and green points) gives an approximation to the value of pi/4. This process is a Monte Carlo simulation approximating pi.
 Let N be the total number of points thrown. When N=50, 100, 200, 300, 500, 1000, 5000, what are the estimated pi values, respectively? For each N, repeat the throwing process 100 times, and report the mean and variance.
 Record the means and the corresponding variances in a table.

Author: Zhang Jinwei
"""


import random as rd


def fail_into():
    x = rd.random()
    y = rd.random()
    radius = (x**2 + y**2) ** 0.5
    return radius


if __name__ == '__main__':
    for i in range(10):
        trail = 20000000
        fail_in_cnt = 0
        for i in range(trail):
            r = fail_into()
            if r < 1:
                fail_in_cnt += 1  # 计算落入圆弧的次数
        """
        正方形面积=1
        1/4圆面积= 1/4 * PI * 1
        """
        print('Took %d Trail, Fail in %d times, estimate PI = %0.06f' % (trail, fail_in_cnt, 4 * fail_in_cnt / trail))
